<template>
  <div class="profile-container">
    <div class="profile-content">
      <h2 class="page-title">个人信息</h2>

      <!-- 基本信息卡片 -->
      <el-card class="info-card">
        <div class="card-header">
          <h3>基本信息</h3>
          <el-button type="primary" link @click="handleEditBasic">修改基本信息</el-button>
        </div>

        <el-form :model="basicInfo" label-width="80px">
          <el-form-item label="姓名">
            <el-input v-model="basicInfo.name" disabled />
          </el-form-item>

          <el-form-item label="性别">
            <el-input v-model="genderText" disabled />
          </el-form-item>

          <el-form-item label="手机号">
            <el-input v-model="basicInfo.mobile" disabled />
          </el-form-item>

          <el-form-item label="邮箱">
            <el-input v-model="basicInfo.email" disabled />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 账号信息卡片 -->
      <el-card class="info-card">
        <div class="card-header">
          <h3>账号信息</h3>
        </div>

        <el-form :model="accountInfo" label-width="80px">
          <el-form-item label="账号">
            <el-input v-model="accountInfo.account" disabled />
          </el-form-item>

          <el-form-item label="密码">
            <div class="input-with-link">
              <el-input v-model="accountInfo.password" type="password" disabled show-password />
              <el-button type="primary" link @click="handleUpdatePassword">修改密码</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 修改基本信息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="修改基本信息"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="editForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirmEdit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
      @close="handlePasswordDialogClose"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirmPassword">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import sysAdminApi from '@/api/sys_admin'
import { useStore } from 'vuex'
import { encryptedData } from '@/utils/jsencrypt'

const store = useStore()
const basicInfo = ref({
  name: '',
  gender: 1,
  mobile: '',
  email: ''
})

const accountInfo = ref({
  account: '',
  password: '********'
})

const dialogVisible = ref(false)
const formRef = ref(null)
const editForm = ref({
  name: '',
  gender: 1,
  mobile: '',
  email: ''
})

const genderText = computed(() => {
  return basicInfo.value.gender === 1 ? '男' : '女'
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

// 获取个人信息
const getUserInfo = async () => {
  try {
    const userId = store.state.app.userId
    if (!userId) {
      ElMessage.error('用户未登录')
      return
    }
    const res = await sysAdminApi.getAdmin({}, userId)
    if (res) {
      if (Array.isArray(res.data)) {
        const data = res.data[0]
        basicInfo.value = {
          name: data.name,
          gender: data.gender,
          mobile: data.mobile,
          email: data.email
        }
        accountInfo.value = {
          account: data.account,
          password: '********'
        }
      }
    }
  } catch (error) {
    console.error('获取个人信息失败:', error)
    ElMessage.error('获取个人信息失败')
  }
}

// 打开编辑对话框
const handleEditBasic = () => {
  editForm.value = { ...basicInfo.value }
  dialogVisible.value = true
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  dialogVisible.value = false
}

// 确认修改
const handleConfirmEdit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const userId = store.state.app.userId
        if (!userId) {
          ElMessage.error('用户未登录')
          return
        }
        const res = await sysAdminApi.updateAdmin(userId, editForm.value)
        if (res) {
          ElMessage.success('修改成功')
          getUserInfo() // 刷新信息
          dialogVisible.value = false
        } else {
          ElMessage.error(res.data?.message || '修改失败')
        }
      } catch (error) {
        console.error('修改失败:', error)
        ElMessage.error('修改失败')
      }
    }
  })
}

// 修改密码相关
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === passwordForm.value.oldPassword) {
          callback(new Error('新密码不能与原密码相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 打开修改密码对话框
const handleUpdatePassword = () => {
  passwordDialogVisible.value = true
}

// 关闭修改密码对话框
const handlePasswordDialogClose = () => {
  passwordFormRef.value?.resetFields()
  passwordDialogVisible.value = false
}

// 确认修改密码
const handleConfirmPassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const userId = store.state.app.userId
        if (!userId) {
          ElMessage.error('用户未登录')
          return
        }
        const password = encryptedData(String(passwordForm.value.newPassword))
        const res = await sysAdminApi.updateAdmin(userId, {
          password: password
        })

        if (res) {
          ElMessage.success('密码修改成功')
          handlePasswordDialogClose()
          // 可选：退出登录，要求用户重新登录
          store.dispatch('app/logout')
        } else {
          ElMessage.error(res.data?.message || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        ElMessage.error('密码修改失败')
      }
    }
  })
}

// 页面加载时获取信息
onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.profile-container {
  height: calc(100vh - 50px);
  overflow-y: auto;
  box-sizing: border-box;
}

.profile-content {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: 600;
  text-align: center;
}

.info-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.input-with-link {
  display: flex;
  align-items: center;
  gap: 10px;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
